package org.taoge;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author weipt
 * @description 数据库连接工具类
 * @date 2024/5/27 22:46
 */
public class DatabaseUtil {
    // 数据库连接参数
    private static final String URL = "jdbc:mysql://localhost:3306/weipt?allowMultiQueries=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=GMT%2B8";
    private static final String USER = "weipt";
    private static final String PASSWORD = "Dev0106..";

    // 静态块用于加载数据库驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动加载失败", e);
        }
    }

    // 私有构造函数，防止外部实例化
    private DatabaseUtil() {}

    /**
     * 获取数据库连接
     * @return Connection 对象
     * @throws SQLException 连接失败时抛出
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        System.out.println("线程："+Thread.currentThread().getId() + "获取数据库链接对象：" +connection);
        return connection;
    }

    /**
     * 关闭数据库连接
     * @param conn 要关闭的数据库连接
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
